.ONESHELL:
projectRoot=$(CURDIR)
projectName=$(shell basename ${CURDIR})
wordCt=$(words ${MAKECMDGOALS})
module=$(word 1,${MAKECMDGOALS})
moduleCmd=$(word 2,${MAKECMDGOALS})
ciTime=$(shell date "+%Y%m%d%H%M%S")

#--------------------------默认变量

#映射家目录
HOMER?=${HOME}

#脚本家目录
ciOutDir?=.cix/build
mkHomer?=.
ciHome=${mkHomer}/.cix
cdRooter?=${HOMER}/.cdx
resHome=${ciHome}/res

#通知
notifyUrl?=https://lb.hubx.dev:5432
entryFile=${ciOutDir}/${module}/entrypoint.sh

#构建方式
T?=docker
#--------------------------end 默认变量

#------------------------校验公共参数------------------------
#变量不允许为空
define var_notnull=
ifeq ($${$(1)},)
$$(error $(1) -> $${$(1)} can't null!!)
endif
endef

define loginfo =
@echo "$$(date -d today +'%Y-%m-%d %T') info: $(1)"
endef

define setOpts =
set -e
set -o pipefail
endef

gVars=ciType imgRepo ciGroup imgTag
$(foreach var,${gVars},$(eval $(call var_notnull,${var})))
#-------------------end 校验公共参数-----------------------------

#--------------------------宏定义------------------------------
#entrypoint.sh模板

define file_import
cat << xEOF >> $(entryFile)

#auto config init file $(1)
mkdir -p ${ciConfigRoot}/$(shell dirname $(1))
cat << EOF > ${ciConfigRoot}/$(1)
xEOF

#content
cat ${resHome}/${module}/$(1) >> $(entryFile)

cat << xEOF >> $(entryFile)

EOF
echo "auto created file: ${ciConfigRoot}/$(1)"
cat  ${ciConfigRoot}/$(1)
xEOF

endef

#生成ci应用元数据
define render_probe
echo "$(1)" |  sed -r "s/:\/\//\//g" | awk -F"/" '{print "\"protocol\":\""$$1"\",\"port\":\""$$2"\",\"uri\":\"" $$3"\""}'
endef
define render_array
kvSpec=($(1)); \
outputs=""; \
output=""; \
for kval in $${kvSpec[*]};\
do \
  if [[ ! -z $${output} ]]; then \
    outputs="$${outputs},";\
    output="$${output},";\
  fi; \
  outputs="$${outputs}\"$${kval%:*}\""; \
  output="$${output}\"$${kval%:*}\":\"$${kval##*:}\""; \
done; \
echo "[$${outputs}],\"$(2)\":{$${output}}";
endef
define render_int_array
kvSpec=($(1)); \
outputs=""; \
output=""; \
for kval in $${kvSpec[*]};\
do \
  if [[ ! -z $${output} ]]; then \
    outputs="$${outputs},";\
    output="$${output},";\
  fi; \
  outputs="$${outputs}\"$${kval%:*}\""; \
  output="$${output}\"$${kval%:*}\":$${kval##*:}"; \
done; \
echo "[$${outputs}],\"$(2)\":{$${output}}";
endef
define render_meta
--label dev.cix.ciType="${ciType}" --label dev.cix.builder="${T}" --label dev.cix.ciVersion="${ciVersion}"
endef #生成ci应用元数据

#加载ci组件定义
define include_ci_template
$$(info load ci file: ${mkHomer}/.cix/$(1).mk)
include ${mkHomer}/.cix/$(1).mk
endef

#加载模块定义,二次展开
define include_module
#针对自举态可以重定义
mDefine=$(filter $(1)=%,${xMods})
$(if $(filter $(1)=%,${xMods}),,$(error module:[$(1)] not defined in mk.mod !!))

modulePath=$$(subst $(1)=,,$${mDefine})
moduleDir=$(CURDIR)/$${modulePath}

#ifneq ($${modulePath},.)
#加载模块
$$(info load module file: $${modulePath}/Makefile)
include $${modulePath}/Makefile
#endif
endef

#--------------------------end宏定义-------------------------

#----------------------有模块参数公共处理---------------------
ifneq (${module},)
#加载模块文件
$(eval $(call include_module,${module}))

gVars=ciContext
$(foreach var,${gVars},$(eval $(call var_notnull,${var})))

endif#------------------end有模块参数公共处理---------------------

#------------->有子命令---------------------------------
ifneq (${moduleCmd},)

imageUrl=${imgRepo}/${ciGroup}/$(if ${imgName},${imgName},${module}):${imgTag}

#包含语言文件
$(eval $(call include_ci_template,${ciType}))

ciMeta=$(call render_meta)

.PHONY: #自动创建构建目录
${ciOutDir}/${module}:
	mkdir -p ${ciOutDir}/${module}

.PHONY: ${module}
${module} : ${ciOutDir}/${module}
	@echo "use module ${module},ciType:${ciType}"

define func_build_image
docker build -f ${moduleDir}/Dockerfile -t ${imageUrl} ${ciContext} ${ciMeta}
endef

define func_push_image
docker --insecure-registry push ${imageUrl}
endef

.ONESHELL: installx
.PHONY: installx
installx :
	if [[ -d ${cdRooter}/${ciGroup}/${module} ]]; then
	  echo '${ciMeta}'>${cdRooter}/${ciGroup}/${module}/cix.json
	  cd  ${cdRooter}/${ciGroup} && cdx ${module} init install imgops=${module}/cix.json
	fi

.PHONY: notifyx
notifyx:
	curl -i ${notifyUrl}/v1/hubx/x/success-build/${module}

.PHONY: notifys
notifys:
	curl -i ${notifyUrl}/v1/hubx/x/start-build/${module}

.PHONY: forward
forward: #ssh转发，开发模式
	ssh -fN -g -R 0.0.0.0:6680:127.0.0.1:6680  root@192.168.1.10

#ciConfigs
.ONESHELL: entryx
entryx: #生成entrypoint.sh脚本
	@set -e
	set -o pipefail
	echo "#!/bin/sh"> $(entryFile)
	$(foreach var,$(ciConfigs),$(call file_import,${var}))
	if [[ -f ${moduleDir}/entrypoint.sh ]]; then
	  cat ${moduleDir}/entrypoint.sh | grep -v "#!/bin"  >> $(entryFile)
	fi
	chmod +x $(entryFile)

endif #<-------------有子命令---------------------

#--------------------只有模块-------------------->
ifeq ($(wordCt),1)
.PHONY: ${module}
.ONESHELL: ${module}
${module}:
	@cat "${modulePath}/Makefile" |  grep '^[^#[:space:]].*:.* #' | awk -F'#'  {'print "--> "$$1  "#"$$2'}
	@echo "    ${ciType}:"
	@grep '^[^#[:space:]].*: .*#' ${mkHomer}/.cix/${ciType}.mk | awk -F'#'  {'print "     --> "$$1  "#"$$2'}

endif #<--------------end 只有模块----------------------

#---------------------无参数--------------------------------
ifeq ($(wordCt),0)

define func_help_all
datas=(${xMods})
for line in $${datas[*]}
do
  modPath=$${line##*=}
  modName=$${line%=*}
  echo $${modName}
  grep '#-' $$modPath/Makefile | awk -F'#-' {'print $$2'}
  grep '^[^#[:space:]].*: #' $${modPath}/Makefile | grep -v ".PHONY" | awk -F'#'  {'print "--> "$$1  "#"$$2'}
  echo ""
done
endef

.ONESHELL: mods
mods:
	@$(call func_help_all)
endif #<---------------------------end 无参数----------------